import pandas as pd

with open('yueyu_1.txt', 'r', encoding='utf-8') as f:
    for line in f.read().replace('\n', '').split('。'):
        pass


# 社交网络图  共现矩阵
# 两个人物出现在同一段，说明有某种关系
words = open('yueyu_1.txt', 'r', encoding='utf-8').read().replace('\n', '').split('。')
words = pd.DataFrame(words, columns=['text'])

nameall = ['迈克尔', '林肯', 'T-bag', '苏克雷', '阿布兹', '萨拉', '维罗妮卡', '贝里克', '克勒曼', 'LJ', '波普', '马宏', '富兰克林', '维斯特莫兰', '尼克',
           '海格威尔']
nameall = pd.DataFrame(nameall,columns = ['name'])

words['wordnum'] = words.text.apply(lambda x: len(x.strip()))

wrods = words.reset_index(drop=True)

relationmat = pd.DataFrame(index=nameall.name.tolist(), columns=nameall.name.tolist()).fillna(0)

wordss = words.text.tolist()
for k in range(len(wordss)):
    for i in nameall.name.tolist():
        for j in nameall.name.tolist():
            if i in wordss[k] and j in wordss[k]:
                relationmat.loc[i, j] += 1
    if k % 1000 == 0:
        print(k)

relationmat.to_excel('共现矩阵.xlsx')

# 网络图


# 边与权重矩阵
# relationmat1 = pd.DataFrame(index = range(relation.shape[]))
relationmat1 = {}
for i in relationmat.columns.tolist():
    for j in relationmat.columns.tolist():
        relationmat1[i, j] = relationmat.loc[i, j]

edgemat = pd.DataFrame(index=range(len(relationmat1)))
node = pd.DataFrame(index=range(len(relationmat1)))

edgemat['Source'] = 0
edgemat['Target'] = 0
edgemat['Weight'] = 0

node['Id'] = 0
node['Label'] = 0
node['Weight'] = 0

names = list(relationmat1.keys())
weights = list(relationmat1.values())
for i in range(edgemat.shape[0]):
    name1 = names[i][0]
    name2 = names[i][1]
    if name1 != name2:
        edgemat.loc[i, 'Source'] = name1
        edgemat.loc[i, 'Target'] = name2
        edgemat.loc[i, 'Weight'] = weights[i]
    else:
        node.loc[i, 'Id'] = name1
        node.loc[i, 'Label'] = name2
        node.loc[i, 'Weight'] = weights[i]
    i += 1

edgemat = edgemat.loc[edgemat.Weight != 0,]
edgemat = edgemat.reset_index(drop=True)
node = node.loc[node.Weight != 0,]
node = node.reset_index(drop=True)



edgemat.to_csv('边.csv',index = False)
node.to_csv('节点.csv',index = False)